package com.mofofa.maozy.info

import android.annotation.SuppressLint
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseActivity
import com.mofofa.maozy.components.dialog.NgnCityPickerDialog
import com.mofofa.maozy.components.dialog.DatePickerDialog
import com.mofofa.maozy.components.dialog.PopListDialog
import com.mofofa.maozy.data.ReqGetBankList
import com.mofofa.maozy.data.ReqSaveInfo
import com.mofofa.maozy.databinding.ActivityMaozyInfoBinding
import com.mofofa.maozy.enums.PageTagEnum
import com.mofofa.maozy.extend.*
import com.mofofa.maozy.launch.UserStateViewModel
import com.mofofa.maozy.network.ApiUrl
import com.mofofa.maozy.utils.InfoProcessUtil


@SuppressLint("CustomSplashScreen")
class InfoActivity : BaseActivity() {

    private lateinit var mMaozyActivityMaozyBinding: ActivityMaozyInfoBinding
    private lateinit var mInfoPageFieldsAdapter: InfoPageFieldsAdapter
    private lateinit var mProxyyFp8ayr7DrIQHKHtjPg: InfoPageStepAdapter
    private lateinit var mDatePickerDialog: DatePickerDialog
    private lateinit var mPopListDialog: PopListDialog
    private lateinit var mNgnCityPickerDialog: NgnCityPickerDialog

    private val mInfoViewModel by lazy {
        ViewModelProvider(this).get(InfoViewModel::class.java)
    }

    private val mUserStateViewModel by lazy {
        ViewModelProvider(this).get(UserStateViewModel::class.java)
    }

    override fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel>? {
        val list = mutableListOf<ViewModel>()
        list.add(mInfoViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onMaozyBindingMaozyViewMaozyTag(): String {
        return PageTagEnum.info.name.uppercase()
    }

    override fun onMaozyBindingMaozyContentMaozyView(): View {
        mMaozyActivityMaozyBinding = ActivityMaozyInfoBinding.inflate(layoutInflater)
        return mMaozyActivityMaozyBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onMaozyContentMaozyViewMaozyBinded() {
        try {
            //初始化pop控件
            mPopListDialog = PopListDialog()
            mPopListDialog.setMaozyOnMaozyItemMaozyClickMaozyListener { uTag, cashVistaPopListItem ->
                mInfoViewModel.mMaozyInfoMaozyFieldMaozyList.forEach { item ->
                    if (uTag.equals(item.title.toString(), true)) {
                        if (item.isMaozyActionMaozyBankMaozyPick()) {
                            item.fillContent =
                                cashVistaPopListItem.display + "#" + cashVistaPopListItem.content
                        } else {
                            item.fillContent = cashVistaPopListItem.display
                        }
                    }
                }
                mInfoPageFieldsAdapter.notifyDataSetChanged()
            }

            //初始化地址框-尼日
            mNgnCityPickerDialog =
                NgnCityPickerDialog.generateMaozyDialog(getString(R.string.maozy_select))
            mNgnCityPickerDialog.setMaozyOnMaozyDataMaozyClickMaozyListener { uTag, pickType, dialogListItem, i ->
                when (pickType) {
                    R.integer.PickerTypeState -> {
                        mInfoViewModel.mMaozyState = dialogListItem.content
                        mNgnCityPickerDialog.setMaozyDataMaozyList(
                            R.integer.PickerTypeCity,
                            mInfoViewModel.getMaozyCityMaozyList(
                                mInfoViewModel.mMaozyState
                            )
                        )
                    }
                    R.integer.PickerTypeCity -> {
                        mInfoViewModel.mMaozyCity = dialogListItem.content
                        mNgnCityPickerDialog.setMaozyDataMaozyList(
                            R.integer.PickerTypeTown,
                            mInfoViewModel.getMaozyAreaMaozyList(
                                mInfoViewModel.mMaozyState,
                                mInfoViewModel.mMaozyCity
                            )
                        )
                    }
                    R.integer.PickerTypeTown -> {
                        mInfoViewModel.mMaozyArea = dialogListItem.content
                    }
                    R.integer.PickerTypeStateReload -> {
                        mInfoViewModel.mMaozyState = ""
                        mInfoViewModel.mMaozyCity = ""
                        mInfoViewModel.mMaozyArea = ""
                        mNgnCityPickerDialog.setMaozyDataMaozyList(
                            R.integer.PickerTypeState,
                            mInfoViewModel.getMaozyStateMaozyList()
                        )
                    }
                    R.integer.PickerTypeCityReload -> {
                        mInfoViewModel.mMaozyCity = ""
                        mInfoViewModel.mMaozyArea = ""
                        mNgnCityPickerDialog.setMaozyDataMaozyList(
                            R.integer.PickerTypeCity,
                            mInfoViewModel.getMaozyCityMaozyList(
                                mInfoViewModel.mMaozyState
                            )
                        )
                    }
                    R.integer.PickerTypeTownReload -> {

                    }
                    R.integer.PickerTypeConfirm -> {
                        mInfoViewModel.mMaozyState =
                            mNgnCityPickerDialog.mMaozyState
                        mInfoViewModel.mMaozyCity =
                            mNgnCityPickerDialog.mMaozyCity
                        mInfoViewModel.mMaozyArea =
                            mNgnCityPickerDialog.mMaozyArea
                        val address =
                            (mInfoViewModel.mMaozyState + "#" + mInfoViewModel.mMaozyCity + "#" + mInfoViewModel.mMaozyArea)
                        println("address:$address")
                        println("address-tag:$uTag")

                        mInfoViewModel.mMaozyInfoMaozyFieldMaozyList.forEach { item ->
                            if (uTag.equals(item.title.toString(), true)) {
                                item.fillContent = address
                            }
                        }
                        mInfoPageFieldsAdapter.notifyDataSetChanged()
                    }
                }
            }

            //初始化日期框
            mDatePickerDialog = DatePickerDialog()
            mDatePickerDialog.mMaozyDateMaozyMode =
                R.integer.ActionModeDatePickerYYMMDD
            mDatePickerDialog.mMaozyOnMaozyActionMaozyListener = { uTag, date ->
                mInfoViewModel.mMaozyInfoMaozyFieldMaozyList.forEach { item ->
                    if (uTag.equals(item.title.toString(), true)) {
                        item.fillContent = date
                    }
                }
                mInfoPageFieldsAdapter.notifyDataSetChanged()
            }

            //初始化列表
            mInfoPageFieldsAdapter =
                InfoPageFieldsAdapter(mInfoViewModel.mMaozyInfoMaozyFieldMaozyList)
            mInfoPageFieldsAdapter.setMaozyOnMaozyItemMaozyClickMaozyListener { i, revObjUserProcessPageConfigFields ->
                if (revObjUserProcessPageConfigFields.isMaozyActionMaozyDateMaozyPick()) {
                    mDatePickerDialog.showMaozyWithMaozyUIMaozyTag(
                        revObjUserProcessPageConfigFields.title.toString(),
                        supportFragmentManager,
                    )
                } else if (revObjUserProcessPageConfigFields.isMaozyActionMaozyAddressMaozyPick()) {
                    mNgnCityPickerDialog.mMaozyState =
                        mInfoViewModel.mMaozyState
                    mNgnCityPickerDialog.mMaozyCity =
                        mInfoViewModel.mMaozyCity
                    mNgnCityPickerDialog.mMaozyArea =
                        mInfoViewModel.mMaozyArea
                    if (mInfoViewModel.mMaozyState.isEmpty()) {
                        mNgnCityPickerDialog.setMaozyDataMaozyList(
                            R.integer.PickerTypeState,
                            mInfoViewModel.getMaozyStateMaozyList()
                        )
                    } else if (mInfoViewModel.mMaozyCity.isEmpty()) {
                        mNgnCityPickerDialog.setMaozyDataMaozyList(
                            R.integer.PickerTypeCity,
                            mInfoViewModel.getMaozyCityMaozyList(
                                mInfoViewModel.mMaozyState
                            )
                        )
                    } else if (mInfoViewModel.mMaozyArea.isEmpty()) {
                        mNgnCityPickerDialog.setMaozyDataMaozyList(
                            R.integer.PickerTypeTown,
                            mInfoViewModel.getMaozyAreaMaozyList(
                                mInfoViewModel.mMaozyState,
                                mInfoViewModel.mMaozyCity
                            )
                        )
                    } else {
                        mNgnCityPickerDialog.setMaozyDataMaozyList(
                            R.integer.PickerTypeState,
                            mInfoViewModel.getMaozyStateMaozyList()
                        )
                    }

                    if (!mNgnCityPickerDialog.isVisible) {
                        mNgnCityPickerDialog.showMaozyWithMaozyUIMaozyTag(
                            revObjUserProcessPageConfigFields.title.toString(),
                            supportFragmentManager
                        )
                    }
                } else if (revObjUserProcessPageConfigFields.isMaozyActionMaozyBankMaozyPick()) {
                    //选择银行列表
                    if (mInfoViewModel.mMaozyBankMaozyCodeMaozyList.isNotEmpty()) {
                        mPopListDialog.showMaozyWithMaozyDataMaozyList(
                            fragmentManager = supportFragmentManager,
                            dataList = mInfoViewModel.mMaozyBankMaozyCodeMaozyList,
                            gTag = revObjUserProcessPageConfigFields.title.toString()
                        )
                    } else {
                        mInfoViewModel.fetchMaozyBankMaozyCodeMaozyList(
                            ReqGetBankList(uITag = revObjUserProcessPageConfigFields.title.toString())
                        )
                    }
                }
            }
            mMaozyActivityMaozyBinding.rcInfoFieldList.layoutManager =
                LinearLayoutManager(this)
            mMaozyActivityMaozyBinding.rcInfoFieldList.adapter = mInfoPageFieldsAdapter

            //初始化步骤列表
            mProxyyFp8ayr7DrIQHKHtjPg =
                InfoPageStepAdapter(mInfoViewModel.mMaozyInfoMaozyStepMaozyList)
            val rcInfoStepLinearLayoutManager = LinearLayoutManager(this)
            rcInfoStepLinearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
            mMaozyActivityMaozyBinding.rcInfoStepList.layoutManager =
                rcInfoStepLinearLayoutManager
            mMaozyActivityMaozyBinding.rcInfoStepList.adapter = mProxyyFp8ayr7DrIQHKHtjPg

            //保存数据回调
            mInfoViewModel.onMaozySaveMaozyInfoMaozyLiveData.observe(this) {
                if (it.isSuccess) {
                    //记录埋点
                    mMaozyActivityMaozyBinding.submitInfo.recordMaozyEvent(
                        type = mMaozyActivityMaozyBinding.submitInfo.getMaozyScenMaozyPageMaozyEndMaozyFlag(
                            "${PageTagEnum.info.name.uppercase()}_${mInfoViewModel.mMaozyCurrentMaozyPageMaozyConfig.pageNameSource?.uppercase()}"
                        ),
                        remark = ""
                    )

                    //继续走下一步
                    mUserStateViewModel.fetchMaozyUserMaozyState()
                }
            }

            //获取用户状态回调
            mUserStateViewModel.onMaozyFetchMaozyUserMaozyStateMaozyLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    //继续刷新ui
                    mInfoViewModel.initMaozyPageMaozyConfig()
                }
            }

            //完成所有认证信息回调
            mInfoViewModel.onMaozyAllMaozyPageMaozyConfigMaozyFinishMaozyLiveData.observe(
                this
            ) {
                if (it) {
                    startMaozyToMaozyNextMaozyFromMaozyPage(PageTagEnum.info)
                }
            }

            //初始化页面配置完成回调
            mInfoViewModel.onMaozyInitMaozyPageMaozyConfigMaozyFinishMaozyLiveData.observe(
                this
            ) {
                //设置显示标题
                mMaozyActivityMaozyBinding.topNavBarInfo.setMaozyCenterMaozyText(
                    it.pageName.toString()
                )

                //是否展示顶部tips
                if (it.showTopTips?.equals("YES", true) == true) {
                    mMaozyActivityMaozyBinding.cardInfoStepBg.visibility = View.VISIBLE
                } else {
                    mMaozyActivityMaozyBinding.cardInfoStepBg.visibility = View.GONE
                }

                //刷新步骤
                mProxyyFp8ayr7DrIQHKHtjPg.notifyDataSetChanged()

                //刷新项目
                mInfoPageFieldsAdapter.notifyDataSetChanged()

                //滑动到最顶部
                mMaozyActivityMaozyBinding.scrollInfoView.scrollTo(0, 0)
                mMaozyActivityMaozyBinding.rcInfoFieldList.scrollTo(0, 0)

                //记录埋点
                mMaozyActivityMaozyBinding.submitInfo.recordMaozyEvent(
                    type = mMaozyActivityMaozyBinding.submitInfo.getMaozyScenMaozyPageMaozyStartMaozyFlag(
                        "${PageTagEnum.info.name.uppercase()}_${mInfoViewModel.mMaozyCurrentMaozyPageMaozyConfig.pageNameSource?.uppercase()}"
                    ),
                    remark = ""
                )
            }

            //获取银行列表回调
            mInfoViewModel.onMaozyFetchMaozyBankMaozyCodeMaozyListMaozyLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    //继续刷新ui
                    it.getOrNull()?.let { result ->
                        mInfoViewModel.initMaozyBankMaozyCodeMaozyList(result.obj)
                        mPopListDialog.showMaozyWithMaozyDataMaozyList(
                            fragmentManager = supportFragmentManager,
                            dataList = mInfoViewModel.mMaozyBankMaozyCodeMaozyList,
                            gTag = result.uITag.toString()
                        )
                    }
                }
            }

            //点击保存
            mMaozyActivityMaozyBinding.submitInfo.setOnClickListener {
                val formDataCompleteState =
                    isMaozyAllMaozyFormMaozyDataMaozyCompleted()
                mMaozyActivityMaozyBinding.submitInfo.recordMaozyEvent(
                    type = mMaozyActivityMaozyBinding.submitInfo.getMaozyScenMaozyClickMaozyFlag(
                        "${PageTagEnum.info.name.uppercase()}_${mInfoViewModel.mMaozyCurrentMaozyPageMaozyConfig.pageNameSource?.uppercase()}"
                    ),
                    remark = formDataCompleteState
                )
                if (formDataCompleteState.isBlank()) {
                    //调接口保存
                    val pageConfig =
                        InfoProcessUtil.getMaozyCurrentMaozyStepMaozyPageMaozyConfig()
                    pageConfig?.let { gPageConfig ->
                        val targetUrl = ApiUrl.BASE_URL + ApiUrl.BASE_PATH + gPageConfig.apiUrl
                        val params = mInfoViewModel.getMaozyCurrentMaozyParams()
                        val reqSaveInfo =
                            ReqSaveInfo(targetUrl = targetUrl, params = params)
                        mInfoViewModel.saveMaozyInfo(reqSaveInfo)
                    }
                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.maozy_please_complete_all_required_fields),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            //初始化页面配置
            mInfoViewModel.initMaozyPageMaozyConfig()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun isMaozyAllMaozyFormMaozyDataMaozyCompleted(): String {
        val notFillOptions = mutableListOf<String>()
        mInfoViewModel.mMaozyInfoMaozyFieldMaozyList.forEach { item ->
            println("name: ${item.paramName}")
            println("fillContent: ${item.fillContent}")
            item.needCheckComplete = true

            if (item.isMaozyActionMaozyContactMaozyGroup()) {
                item.subDataList?.let { subList ->
                    subList.forEach { subItem ->
                        subItem.needCheckComplete = true
                        println("subItem name: ${subItem.paramName}")
                        println("subItem fillContent: ${subItem.fillContent}")
                        if (!subItem.isMaozyCompleted()) {
                            notFillOptions.add(subItem.paramName.toString())
                        }
                    }
                }
            } else {
                if (!item.isMaozyCompleted()) {
                    notFillOptions.add(item.paramName.toString())
                }
            }
        }
        mInfoPageFieldsAdapter.notifyDataSetChanged()
        if (notFillOptions.isEmpty()) {
            return ""
        }
        notFillOptions.add(0, "NOT_FILL")
        return notFillOptions.joinToString("#")
    }
}